<template>
  <div class="container">
    <form @submit.prevent="createCalculator()" class="mt-5 mb-5">
      <div class="mb-1">
        <label for="name" class="form-label">Назва кредиту</label>
        <input type="text" class="form-control" id="name" v-model="name" :class="{'is-valid': nameValid, 'is-invalid': !nameValid}">
        <div class="invalid-feedback">
          Ім'я має бути 4-255 символів
        </div>
      </div>
      <div class="mb-1" v-show="nameValid">
        <label for="rate" class="form-label">Банк</label>
        <select class="d-block form-select" name="bank" id="bank" v-model="bank_id" :class="{'is-valid': bankValid, 'is-invalid': !bankValid}">
          <option value="null">Оберіть банк</option>
          <option v-for="bank in banks" :key="bank.name" :value="bank.id">{{bank.name}}</option>
        </select>
      </div>
      <div class="mb-1" v-show="bankValid">
        <label for="initial_loan" class="form-label">Початковий кредит</label>
        <input type="text" class="form-control" id="initial_loan" v-model="initial_loan" :class="{'is-valid': creditValid, 'is-invalid': !creditValid}">
        <div :class="{'invalid-feedback': maxLoan, 'visually-hidden': !maxLoan}">
          Мінімальний кредит, який може надати банк {{minLoan}}$, максимальний {{maxLoan}}$
        </div>
        <div :class="{'invalid-feedback': !maxLoan, 'visually-hidden': maxLoan > 0}">
          Введіть суму кредиту
        </div>
      </div>
      <div class="mb-1" v-show="creditValid">
        <label for="down_payment" class="form-label">Початковий внесок</label>
        <input type="text" class="form-control" id="down_payment" v-model="down_payment" :class="{'is-valid': downPaymentValid, 'is-invalid': !downPaymentValid}">
        <div :class="{'invalid-feedback': minDownPayment, 'visually-hidden': !minDownPayment}">
          Мінмальний аванс {{minDownPayment}}$
        </div>
        <div :class="{'invalid-feedback': !minDownPayment, 'visually-hidden': minDownPayment > 0}">
          Введіть початковий внесок
        </div>
      </div>
      <div class="mb-2" v-show="downPaymentValid && bankValid">
        <label for="term" class="form-label">Термін</label>
        <input type="text" class="form-control" id="term" v-model="term" :class="{'is-valid': termValid, 'is-invalid': !termValid}">
        <div :class="{'invalid-feedback': maxTerm, 'visually-hidden': !maxTerm}">
          Максимальний термін {{maxTerm}}
        </div>
        <div :class="{'invalid-feedback': !maxTerm, 'visually-hidden': maxTerm > 0}">
          Введіть термін
        </div>
      </div>
      <button type="submit" class="btn btn-primary" :class="{'disabled': !allValid}">Створити розрахунок</button>
    </form>
    <div class="mt-3 d-flex flex-wrap gap-3">
      <div class="card mb-3" style="width: 18rem;" v-for="calculator in calculators" :key="calculator.id">
        <div class="card-body">
          <h5 class="card-title">{{calculator.name}}</h5>
            <ul class="list-group list-group-flush mb-3">
              <li class="list-group-item p-0">Початковий кредит: {{calculator.initial_loan}}$</li>
              <li class="list-group-item p-0">Початковий внесок: {{calculator.down_payment}}$</li>
              <li class="list-group-item p-0">Відсоткова ставка: {{getRate(calculator.bank_id)}}%</li>
              <li class="list-group-item p-0">Термін: {{calculator.term}} місяців</li>
            </ul>
          <router-link class="card-link" :to="{name: 'showCalculator', params: {calculatorId: calculator.id}}">
            Переглянути
          </router-link>
          <a href="#" class="card-link link-danger" @click.prevent="removeCalculator(calculator.id)">Видалити</a>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      banks: {},
      calculators: {

      },
      name: null,
      bank_id: null,
      initial_loan: null,
      down_payment: null,
      term: null,
    }
  },
  computed: {
    nameValid() {
      if(this.name) {
        return this.name.length > 3 && this.name.length < 255
      }
    },
    bankValid() {
      return this.bank_id > 0
    },
    maxLoan(){
      if(this.bank_id > 0 && this.initial_loan) {
        return this.banks[this.bank_id-1].max_loan //in the database id starts with 1, and in the object with 0
      }
      return false
    },
    minLoan() {
      return this.minDownPayment * 3
    },
    creditValid() {
      return (this.maxLoan > this.initial_loan && this.initial_loan > this.minLoan)
    },
    minDownPayment(){
      if(this.bank_id > 0) {
        return this.banks[this.bank_id-1].min_down_payment //in the database id starts with 1, and in the object with 0
      }
      return false
    },
    downPaymentValid() {
      return (this.down_payment >= this.minDownPayment)
    },
    maxTerm () {
      if(this.bank_id > 0 && this.term) {
        return this.banks[this.bank_id-1].max_term //in the database id starts with 1, and in the object with 0
      }
      return false
    },
    termValid () {
      return (0 < this.term && this.term <= this.maxTerm)
    },
    allValid () {
      return (this.nameValid && this.bankValid && this.creditValid && this.downPaymentValid && this.termValid)
    }
  },
  methods: {
    getBanks() {
      axios.get('/api/v1/banks/')
        .then(response => {
          this.banks = response.data.data
        })
        .catch(error => {
          console.error(error)
          this.errored = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    getRate(id) {
      let bank = this.banks[id-1]
      return bank.rate
    },
    getCalculators() {
      axios.get('/api/v1/calculators/')
        .then(response => {
          this.calculators = response.data.data
        })
        .catch(error => {
          console.error(error)
          this.errored = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    createCalculator() {
      axios.post('/api/v1/calculators/', {
        name: this.name,
        bank_id: this.bank_id,
        initial_loan: this.initial_loan,
        down_payment: this.down_payment,
        term: this.term,
      })
        .then(response => {
          this.calculators = {}
          this.name = null
          this.bank_id = null
          this.initial_loan = null
          this.down_payment = null
          this.term = null
          this.getCalculators()
        })
        .catch(error => {
          console.error(error)
          this.errored = true
        })
        .finally(() => {
          this.loading = false
        })
    },
    removeCalculator(id) {
      axios.post('/api/v1/calculators/'+id, {
        _method: 'DELETE'
      })
        .then(response => {
          this.calculators = {}
          this.getCalculators()
        })
        .catch(error => {
          console.error(error)
          this.errored = true
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
  mounted() {
    this.getBanks()
    this.getCalculators()
  }
}
</script>

<style>

</style>